Show solution
library(ggplot2)
<- ggplot(mtcars, aes(x=wt, y=mpg)) +
p1 geom_point() +
ggtitle("Miles per Gallon vs. Weight") +
xlab("Weight") +
ylab("Miles per Gallon")
print(p1)
ggplot2
The following exercises are designed to encourage you to become familiar with plotting in ggplot2
. They all use datasets that are available from within base R, or within the ggplot2
package.
I’ve provided solutions to each of these exercises. Please remember that R is a hugely flexible language and there are often lots of different ways to achieve the same outcome!
ggplot2
library(ggplot2)
<- ggplot(mtcars, aes(x=wt, y=mpg)) +
p1 geom_point() +
ggtitle("Miles per Gallon vs. Weight") +
xlab("Weight") +
ylab("Miles per Gallon")
print(p1)
geoms
<- ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
p2 geom_point() +
geom_smooth(method='lm', se=FALSE)
print(p2)
`geom_smooth()` using formula = 'y ~ x'
facet_wrap()
.<- ggplot(diamonds, aes(x=carat, y=price)) +
p3 geom_point() +
facet_wrap(~cut, scales="free_y")
print(p3)
theme_minimal()
function to change its appearance.<- ggplot(mtcars, aes(x=wt, y=mpg)) +
p4 geom_point() +
theme_minimal()
print(p4)
<- ggplot(diamonds, aes(x=cut)) +
p5 geom_bar() +
coord_flip()
print(p5)
<- ggplot(diamonds, aes(x=price)) +
p6 geom_histogram(binwidth=500)
print(p6)
<- ggplot(iris, aes(x=Species, y=Sepal.Length, color=Species)) +
p7 geom_boxplot(outlier.color="red")
print(p7)
<- ggplot(mpg, aes(x=class, fill=drv)) +
p8 geom_bar(position="dodge")
print(p8)
<- ggplot(mpg, aes(x=displ, y=hwy, color=class)) +
p9 geom_point() +
labs(color="Car Class") +
theme(legend.position="bottom")
print(p9)
# Save the first plot as a PNG
ggsave(filename="p1_plot.png", plot=p1, width=6, height=4, dpi=300)
# Save the first plot as a PDF
ggsave(filename="p1_plot.pdf", plot=p1, width=6, height=4)